package com.kaplan.hackathon;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.lang.model.util.ElementFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.xml.sax.SAXException;

import com.google.gson.Gson;
import com.kaplan.hackathon.models.Content;
import com.kaplan.hackathon.models.LearningPodContent;
import com.kaplan.hackathon.models.SimpleChoice;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class LearningPodService {
	private static final Log log = LogFactory.getLog(LearningPodService.class);
	
	private String clientId = "c196e47968d4f813e653";
	private String clientSecret = "9f326bc79a5e5e40ccb06bcb40a23cbb48f45c70";
	
	
	public Content getQuestionTitle(String id) {
		log.info(" ==== Inside getQustionTitle: uuid: " + id);
		Client client = Client.create();
		
		Content content = new Content();
		
		String url = "https://core.learningpod.com/api/content/"+id + "/meta?client_id=c196e47968d4f813e653&client_secret=9f326bc79a5e5e40ccb06bcb40a23cbb48f45c70";
		WebResource webResource = client.resource(url);
		Map<String, String> responseMap = new HashMap<String, String>();
		Gson gson = new Gson();
		ClientResponse res = webResource.accept("application/json").get(ClientResponse.class);
		String response = res.getEntity(String.class);
		
		responseMap = gson.fromJson(response, HashMap.class);
		log.info(response);
		content.setTitle(responseMap.get("title"));
		content.setType(responseMap.get("subType"));
		return content;
	}
	
	public Content getQuestionByUUID(String id) {
		log.info(" ==== Inside getQustion Method: uuid: " + id);
		Content content = new Content();
		
		Client client = Client.create();
		content = this.getQuestionTitle(id);
		String url = "https://core.learningpod.com/api/content/"+id + "?client_id=c196e47968d4f813e653&client_secret=9f326bc79a5e5e40ccb06bcb40a23cbb48f45c70";
		WebResource webResource = client.resource(url);
		
		ClientResponse res = webResource.accept("application/json").get(ClientResponse.class);
		String xmlContent = res.getEntity(String.class);
		log.info(xmlContent);
		
		String questionBody = StringUtils.substringBetween(xmlContent, "<questionBody>", "</questionBody>");
		content.setQuestion(questionBody);
		String answerChoices = StringUtils.substringBetween(xmlContent,"<choiceInteraction", "</choiceInteraction>");
		log.info("==" + answerChoices);
		
		JSONObject xmlJson;
		try {
			
			//Serializer serializer = new Persister();
			//LearningPodContent cont = serializer.read(LearningPodContent.class, xmlContent);
			
			//log.info("**** : " + cont.getChoiceQuestion());
			
			SAXBuilder builder = new SAXBuilder();
			
			Document document = (Document) builder.build(new ByteArrayInputStream(xmlContent.getBytes("utf-8")));
			
			Element rootNode = document.getRootElement();
			
			Element choiceQuestion = rootNode.getChild("choiceQuestion");
			
			Element choiceInteraction = choiceQuestion.getChild("choiceInteraction");
			log.info("==== " +choiceInteraction.getChildren().size());
			
			List<Element> simpleChoices = choiceInteraction.getChildren();
			
			for (int i=0; i<simpleChoices.size(); i++) {
				Element temp = simpleChoices.get(i);
				log.info("========== " + temp.getAttributeValue("choiceId"));
				log.info("*** " + temp.getChild("p").getText());
				log.info("=== " + temp.getAttributeValue("correct"));
				
				SimpleChoice choice = new SimpleChoice();
				choice.setCorrect(Boolean.getBoolean(temp.getAttributeValue("correct")));
				choice.setChoiceId(temp.getAttributeValue("choiceId"));
				choice.setAnswer(temp.getChild("p").getText());
				content.addQuestionChoice(choice);
				//content.addQuestionChoice(temp.getChild("p").getText());
			}
			/*
			xmlJson = XML.toJSONObject(xmlContent);
			log.info(xmlJson.toString());
			Map<String, Object> map = new HashMap<String, Object>();
			Gson gson = new Gson();
			map = gson.fromJson(xmlJson.toString(), HashMap.class);
			Iterator it = map.entrySet().iterator();
			log.info("===========");
			String choices = xmlJson.getJSONObject("learningpod").getJSONObject("choiceQuestion").getString("choiceInteraction");
			log.info(choices);
			*/
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//log.info(questionBody);
		return content;
	}

	
	
	public String searchQuestionByKeyword(String keyword) {
		log.info(" ==== Inside getQustion Method: uuid: " + keyword);
		Client client = Client.create();
		
		String url = "https://core.learningpod.com/api/content/search?q=excel&client_id=c196e47968d4f813e653&client_secret=9f326bc79a5e5e40ccb06bcb40a23cbb48f45c70";
		WebResource webResource = client.resource(url);
		
		Gson gson = new Gson();
		
		ClientResponse res = webResource.accept("application/json").get(ClientResponse.class);
		String questionsList = (res.getEntity(String.class));
		log.info(questionsList);
		
		return questionsList;
	}
	
}
